<template>
  <div class="space-y-8">
    <!-- 日期筛选器 -->
    <n-card size="small" :bordered="false" class="filter-card">
      <div class="flex items-center gap-4">
        <span class="text-sm font-medium text-gray-700">查询特定日期的支委任职情况：</span>
        <n-date-picker
          v-model:formatted-value="selectedDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择日期"
          clearable
          @update:value="handleDateChange"
        />
        <n-button size="small" type="primary" @click="handleDateQuery">
          查询
        </n-button>
        <n-button size="small" @click="clearDateFilter">
          清除筛选
        </n-button>
      </div>
    </n-card>

    <!-- 查询结果 -->
    <n-card v-if="dateQueryResult" size="small" :bordered="false" class="query-result-card">
      <template #header>
        <div class="flex items-center gap-2">
          <n-icon class="text-blue-500"><SearchIcon /></n-icon>
          <span>{{ selectedDate }} 的支委任职情况</span>
        </div>
      </template>
      <div v-if="dateQueryResult.committee">
        <p class="mb-3">该日期属于第{{ dateQueryResult.termNumber }}届支委任期</p>
        <n-tag type="info" round class="mb-3">
          <template #icon><n-icon :component="CalendarIcon" /></template>
          {{ formatDate(dateQueryResult.committee.startDate) }} - {{ formatDate(dateQueryResult.committee.endDate) || '至今' }}
        </n-tag>
        <div class="space-y-2">
          <div v-for="member in dateQueryResult.committee.committeeMembers" :key="member.memberId" class="flex items-center gap-2">
            <n-avatar round size="small"><n-icon :component="PersonIcon"/></n-avatar>
            <span>{{ member.memberName }}</span>
            <n-tag :bordered="false" :type="getPositionTagType(member.positionHeld)" size="small">{{ member.positionHeld }}</n-tag>
          </div>
        </div>
      </div>
      <div v-else>
        <p class="text-gray-500">该日期没有支委任职记录</p>
      </div>
    </n-card>

    <!-- 当前支委信息 -->
    <div v-if="currentCommittee && !dateQueryResult">
      <h3 class="text-lg font-semibold text-gray-800 border-b border-gray-200 pb-3 mb-4 flex items-center gap-2">
        <n-icon class="text-green-500"><StarIcon /></n-icon>
        <span>当前在任支委</span>
      </h3>
      <n-card class="current-committee-card" :bordered="false">
        <div class="flex justify-between items-center mb-4">
          <n-space align="center">
            <n-tag type="success" round>
              <template #icon><n-icon :component="CalendarIcon" /></template>
              {{ formatDate(currentCommittee.startDate) }} - 至今
            </n-tag>
          </n-space>
          <n-tag :type="currentCommittee.committeeMembers.length > 0 ? 'success' : 'warning'" round>
             <template #icon><n-icon :component="PeopleIcon" /></template>
            {{ currentCommittee.committeeMembers.length }} 人
          </n-tag>
        </div>
        <!-- 成员列表 -->
        <div class="space-y-3">
          <n-card v-for="member in currentCommittee.committeeMembers" :key="member.memberId" size="small" :bordered="false" class="member-card">
            <div class="flex items-center justify-between">
              <n-space align="center">
                <n-avatar round size="small"><n-icon :component="PersonIcon"/></n-avatar>
                <span class="font-semibold">{{ member.memberName }}</span>
                <n-tag :bordered="false" :type="getPositionTagType(member.positionHeld)" size="small">{{ member.positionHeld }}</n-tag>
              </n-space>
              <span class="text-sm text-gray-500">{{ member.phoneNumber || '暂无联系方式' }}</span>
            </div>
          </n-card>
        </div>
      </n-card>
    </div>

    <!-- 历届支委信息 -->
    <div v-if="historicalCommittees.length > 0 && !dateQueryResult">
      <h3 class="text-lg font-semibold text-gray-800 border-b border-gray-200 pb-3 mb-4 flex items-center gap-2">
        <n-icon class="text-gray-500"><HistoryIcon /></n-icon>
        <span>历届支委</span>
      </h3>
      <div class="relative pl-4 border-l-2 border-slate-200 space-y-6">
         <n-card v-for="(committee, index) in historicalCommittees" :key="committee.committeeId" class="historical-committee-card" hoverable>
            <!-- 时间轴上的圆点 -->
            <div class="absolute -left-[9px] top-5 w-4 h-4 bg-white border-2 border-slate-300 rounded-full"></div>
            <template #header>
               <div class="flex justify-between items-center">
                <n-space align="center">
                  <n-tag type="default" round>第{{ historicalCommittees.length - index }}届</n-tag>
                  <span class="text-sm text-gray-600">
                    {{ formatDate(committee.startDate) }} - {{ formatDate(committee.endDate) }}
                  </span>
                </n-space>
                 <n-space>
                    <n-button size="tiny" secondary @click="emit('edit-committee', committee)">
                      <template #icon><n-icon :component="EditIcon"/></template>
                      编辑
                    </n-button>
                    <n-button size="tiny" type="error" ghost @click="emit('delete-committee', committee)">
                       <template #icon><n-icon :component="DeleteIcon"/></template>
                      删除
                    </n-button>
                 </n-space>
               </div>
            </template>
            <!-- 成员列表 -->
            <div class="space-y-3">
              <n-card v-for="member in committee.committeeMembers" :key="member.memberId" size="small" :bordered="false" class="member-card-historical">
                 <div class="flex items-center justify-between">
                  <n-space align="center">
                    <n-avatar round size="small" color="#f0f0f0" text-color="#666"><n-icon :component="PersonIcon"/></n-avatar>
                    <span class="font-semibold text-gray-700">{{ member.memberName }}</span>
                    <n-tag :bordered="false" :type="getPositionTagType(member.positionHeld)" size="small">{{ member.positionHeld }}</n-tag>
                  </n-space>
                  <span class="text-sm text-gray-500">{{ member.phoneNumber || '暂无' }}</span>
                </div>
              </n-card>
            </div>
         </n-card>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-if="(!committees || committees.length === 0) && !dateQueryResult" class="text-center py-12 text-gray-500">
      <n-icon size="48" class="mb-4 text-gray-300" :component="PeopleTeamIcon" />
      <p class="text-base">暂无任何支委信息</p>
      <p class="text-sm mt-2">您可以点击右上方的 "新增支委" 按钮来创建第一届支委</p>
    </div>
  </div>
</template>

<script setup>
import { NCard, NButton, NIcon, NTag, NSpace, NAvatar, NDatePicker } from 'naive-ui'
import { computed, ref } from 'vue'
import {
  StarOutline as StarIcon,
  PeopleOutline as PeopleIcon,
  CalendarOutline as CalendarIcon,
  PersonOutline as PersonIcon,
  TimeOutline as HistoryIcon,
  CreateOutline as EditIcon,
  TrashOutline as DeleteIcon,
  People as PeopleTeamIcon,
  SearchOutline as SearchIcon,
} from '@vicons/ionicons5'

const props = defineProps({
  committees: { type: Array, default: () => [] }
})

// 修改点：定义清晰的 emit 事件
const emit = defineEmits(['edit-committee', 'delete-committee'])

// 日期筛选相关状态
const selectedDate = ref(null)
const dateQueryResult = ref(null)

// --- 工具函数 ---
const formatDate = (dateStr) => {
  if (!dateStr) return '未知日期';
  try {
    const date = new Date(dateStr);
    return date.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' });
  } catch (e) {
    return dateStr;
  }
}

const getPositionTagType = (position) => {
  const typeMap = {
    '支部书记': 'error',
    '副书记': 'warning',
    '组织委员': 'info',
    '宣传委员': 'success',
    '纪检委员': 'default'
  };
  return typeMap[position] || 'default';
}

// --- 计算属性 ---
const currentCommittee = computed(() => {
  return props.committees.find(c => !c.endDate)
})

const historicalCommittees = computed(() => {
  return props.committees
    .filter(c => c.endDate)
    .sort((a, b) => new Date(b.startDate) - new Date(a.startDate)) // 按开始日期降序排列
})

// 日期筛选功能
const handleDateChange = (value) => {
  selectedDate.value = value
}

const handleDateQuery = () => {
  if (!selectedDate.value) {
    return
  }
  
  const queryDate = new Date(selectedDate.value)
  
  // 查找该日期属于哪一届支委
  let foundCommittee = null
  let termNumber = 0
  
  // 先检查当前支委
  if (currentCommittee.value) {
    const startDate = new Date(currentCommittee.value.startDate)
    if (queryDate >= startDate) {
      foundCommittee = currentCommittee.value
      termNumber = 1
    }
  }
  
  // 如果不在当前支委任期内，检查历届支委
  if (!foundCommittee) {
    for (let i = 0; i < historicalCommittees.value.length; i++) {
      const committee = historicalCommittees.value[i]
      const startDate = new Date(committee.startDate)
      const endDate = new Date(committee.endDate)
      
      if (queryDate >= startDate && queryDate <= endDate) {
        foundCommittee = committee
        termNumber = i + 2 // 第2届开始
        break
      }
    }
  }
  
  dateQueryResult.value = {
    committee: foundCommittee,
    termNumber: termNumber
  }
}

const clearDateFilter = () => {
  selectedDate.value = null
  dateQueryResult.value = null
}
</script>

<style scoped>
.current-committee-card {
  background: linear-gradient(135deg, #f0faff 0%, #e6f7ff 100%);
  border-left: 4px solid #2d8cf0;
}
.historical-committee-card {
  background-color: #fcfcfc;
}
.member-card {
  background-color: #ffffff;
  border-radius: 6px;
}
.member-card-historical {
  background-color: #f5f5f5;
   border-radius: 6px;
}
.filter-card {
  background-color: #f8f9fa;
  border: 1px solid #e9ecef;
}
.query-result-card {
  background-color: #e6f7ff;
  border-left: 4px solid #1890ff;
}
</style>